package me.biezhi.longweibo.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.biezhi.longweibo.util.ConvertUtil;
import me.biezhi.longweibo.util.HttpUtil;

/**
 * Servlet implementation class ConvertServlet
 */
@WebServlet(urlPatterns = "/covert_toimg", asyncSupported=false)
public class ConvertServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String head = "<!DOCTYPE HTML>\r\n<html>"
			+ "\r\n		<head>"
			+ "\r\n			<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>"
			+ "\r\n		</head>\r\n<body>\r\n";
	private static final String foot = "\r\n</body>\r\n</html>";

	public ConvertServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		HttpUtil http = new HttpUtil(request);
		Integer type = http.getParaToInt("type");
		Integer width = http.getParaToInt("width");
		Integer height = http.getParaToInt("height");
		
		// 设置长微博图的尺寸
		if(null != width && null != height){
			ConvertUtil.MIN_WIDTH = width;
			ConvertUtil.MIN_HEIGHT = height;
		}
		String content = http.getPara("content");
		final String rootPath = http.getRootPath();
		final String rootUrl = http.getBaseUrl();
		
		Long currtime = System.currentTimeMillis();
		String html = null;
		
		// 保存html
		if(null != type && type == 1){
			html = head + content + foot;
			ConvertUtil.writeHtml(rootPath, currtime + ".html", html);
		}
		// 长微博的图片保存位置 WebRoot/images/1245565.png
		String imgPath = rootPath + "images" + File.separator + currtime + ".png";
		
		// url 1：localhost/html/1232131312.html		2:http://www.baidu.com
		String url = (type==1) ? rootUrl + "/html/" + currtime + ".html" : content;
		
		// 转换为图片格式
		if(ConvertUtil.exec(url, imgPath)){
			String imgUrl = rootUrl + "/images/" + currtime + ".png";
			System.out.println("img = " + imgUrl);
			if(null != type && type == 1){
				ConvertUtil.removeHtml(rootPath + "/html/" + currtime + ".html");
			}
			http.print(response, imgUrl);
		}
	}
	
}
